﻿using Sustainalytics.Entities;

namespace Sustainalytics.DataLayer.Shared
{
    public static class UserExtensions
    {
        public static void AdaptEmailToStatus(this User user, IAccountsRepository accountRepository)
        {
            if (user.Status == Status.Inactive)
                user.Email = GetEmailForInactive(user.Email, accountRepository);
            else
                user.Email = GetEmailForActive(user.Email);
        }

        private static string GetEmailForInactive(string email, IAccountsRepository accountRepository)
        {
            User user;
            string newEmail;
            if (email.IndexOf('*') != -1) //already changed
                return email;

            newEmail = email;

            do
            {
                newEmail = newEmail.Insert(0, "*");

                user = accountRepository.TryGetUserByUsername(newEmail);
            }
            while (user != null);

            return newEmail;
        }

        private static string GetEmailForActive(string email)
        {
            var ind = email.LastIndexOf('*');
            if (ind == -1) //not changed
                return email;

            return email.Remove(0, ind + 1);
        }

    }
}
